package com.enjoyor.soa.traffic.frame.support.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;

import com.enjoyor.soa.traffic.util.helper.LoggerHelper;

/**
 * @Author：周宏伟
 * @Email：zhouhongwei@enjoyor.net
 * @DateTime：2016年2月24日 @Description：Properties文件操作类
 */
public class PropertiesUtil {
    /**
     * 获取properties键值
     * 
     * @param name
     *            properties名称
     * @return properties键值
     */
    public static Map<String, String> getProperties(String name) {
        Map<String, String> map = new HashMap<String, String>();
        InputStream is = null;
        try {
            is = new ClassPathResource(name + ".properties").getInputStream();
            Properties p = new Properties();
            p.load(is);
            Enumeration<?> e = p.propertyNames();
            while (e.hasMoreElements()) {
                String key = e.nextElement().toString();
                map.put(key, p.getProperty(key));
            }
        } catch (IOException e) {
            LoggerHelper.LOG.error(e.getMessage());
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                LoggerHelper.LOG.error(e.getMessage());
            }
        }
        return map;
    }

    /**
     * 获取properties值
     * 
     * @param name
     *            properties名称
     * @param key
     *            properties键
     * @return properties值
     */
    public static String getProperties(String name, String key) {
        Map<String, String> map = getProperties(name);
        if (map != null && !map.isEmpty() && map.containsKey(key)) {
            return map.get(key);
        }
        return null;
    }

    /**
     * 获取resource.properties
     * 
     * @param key
     *            resource.properties键
     * @return resource.properties值
     */
    public static String getResourceProperties(String key) {
        Map<String, String> map = getProperties("resources");
        if (map != null && !map.isEmpty() && map.containsKey(key)) {
            return map.get(key);
        }
        return null;
    }

    /**
     * 获取config.properties
     * 
     * @param key
     *            config.properties键
     * @return config.properties值
     */
    public static String getConfigProperties(String key) {
        Map<String, String> map = getProperties("config");
        if (map != null && !map.isEmpty() && map.containsKey(key)) {
            return map.get(key);
        }
        return null;
    }
}
